#!/bin/bash
# Job yaml can send below ENVIRONMENT VARIABLES to me
# - lkvs_repo
# - lkvs_checkout
# - feature
# END ENVIRONMENT VARIABLES

echo "Cloning source code from $lkvs_repo..."

: "${feature:='none'}"
: "${srcdir:='none'}"


declare -A run_funcs

run_funcs["ifs"]=run_tests
run_funcs["isst"]=run_tests
run_funcs["pmu"]=run_tests
run_funcs["sdsi"]=run_tests
run_funcs["ufs"]=run_tests
run_funcs["cstate"]=run_cstate
run_funcs["rapl"]=run_rapl
run_funcs["topology"]=run_topology
run_funcs["pt"]=run_pt
run_funcs["umip"]=run_umip
run_funcs["splitlock"]=run_splitlock
run_funcs["xsave"]=run_xsave
run_funcs["thermal"]=run_thermal

run_tests() {
  cd $srcdir
  ./runtests -f $1/tests -o ./result/results_$1.log
}

run_cstate() {
  cd $srcdir
  ./runtests -f cstate/tests-server -o ./result/results_cstate_server.log
#  ./runtests -f cstate/tests-client -o ./result/results_cstate_client.log
  return
}

run_rapl() {
  cd $srcdir
  ./runtests -f rapl/tests-server -o ./result/results_rapl_server.log
#  ./runtests -f rapl/tests-client -o ./result/results_rapl_client.log
  return
}

run_topology() {
  cd $srcdir
  ./runtests -f topology/tests-server -o ./result/results_topology_server.log
#  ./runtests -f topology/tests-client -o ./result/results_topology_client.log
  return
}

run_pt() {
  cd $srcdir/pt
  make
  cd ..
  ./runtests -f pt/tests -o ./result/results_pt.log
  return
}

run_umip() {
  cd $srcdir/umip
  make
  cd ..
  ./runtests -f umip/tests -o ./result/results_umip.log
  return
}

run_splitlock() {
  cd $srcdir/splitlock
  make
  cd ..
  ./runtests -f splitlock/tests -o ./result/results_splitlock.log
  return
}

run_xsave() {
  cd $srcdir/xsave
  make
  cd ..
  ./runtests -f xsave/tests -o ./result/results_xsave.log
  return
}

run_thermal() {
  cd $srcdir
  ./runtests -f thermal/thermal-tests -o ./result/results_thermal.log
  return
}

retry=0
max_retries=3
while ((retry<max_retries))
do
    git clone $lkvs_repo $TMP/lkvs && break
    retry=$((retry+1))
    echo "Git clone failed, retrying... ($retry/$max_retries)"
    sleep 5
done

if ((retry==max_retries)); then
    echo "Git clone failed after $max_retries attempts, exiting..."
    exit 1
fi

echo "Code downloaded, checking out to $lkvs_checkout..."
cd $TMP/lkvs && git checkout $lkvs_checkout || exit 1
echo "Ready."

if [[ -z $feature ]]; then
    echo "Feature to test could not be empty" && \
    exit 1
elif [[ ! -d $TMP/lkvs/$feature ]]; then
    echo "$feature does not exist in $lkvs_repo@$lkvs_checkout" && \
    exit 1
fi

echo "Running LKVS for testing $feature..."
if [[ -n "${run_funcs[$feature]}" ]]; then
    ${run_funcs[$feature]} "$feature"
else
    echo "Invalid feature: $feature"
    exit 1
fi
echo "Done."
